package com.zhende.hr.utils;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.zhende.hr.entity.CustomUserDetails;
import com.zhende.hr.service.impl.CustomUserDetailsService;

@Component
public class JwtTokenProvider {

    @Autowired
    private CustomUserDetailsService userDetailsService;

    private static final String SECRET_KEY = "fmf123456";  // 你的密钥

    private static final long VALIDITY_IN_MS = 1000* 60; //  * 60 * 60 * 2;  // Token 的有效期，2小时

    // 根据认证信息生成 JWT Token
    public String generateToken(Authentication authentication) {
        CustomUserDetails userPrincipal = (CustomUserDetails) authentication.getPrincipal();
        Date now = new Date();
        Date expiryDate = new Date(now.getTime() + VALIDITY_IN_MS);

        return JWT.create()
                .withSubject(userPrincipal.getUsername())
                .withClaim("uuid", userPrincipal.getUuid())  // 假设 CustomUserDetails 有 uuid 字段
                .withIssuedAt(now)
                .withExpiresAt(expiryDate)
                .sign(Algorithm.HMAC256(SECRET_KEY));
    }

    // 解析 JWT Token，获取认证信息
    public Authentication getAuthentication(String token) {
        DecodedJWT decodedJWT = JWT.decode(token);
        String uuid = decodedJWT.getClaim("uuid").asString();

        // 使用 UUID 获取用户信息
        CustomUserDetails userDetails = userDetailsService.loadUserByUuid(uuid);

        return new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
    }

    // 验证 Token 是否有效
    public boolean validateToken(String token) {
        try {
            DecodedJWT decodedJWT = JWT.decode(token);
            return !decodedJWT.getExpiresAt().before(new Date());
        } catch (Exception e) {
            return false;
        }
    }
}

